package com.gitee.fsmxm.thinking.in.spring.dependency.lookup;

import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * ObjectProvider 获取bean demo
 */
public class HierarchicalDependencyLookupDemo {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        applicationContext.register(HierarchicalDependencyLookupDemo.class);

        ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();

        // 设置父bean工厂
        HierarchicalBeanFactory parentBeanFactory = loadBeanFactory();
        beanFactory.setParentBeanFactory(parentBeanFactory);

        applicationContext.refresh();

        // containsLocalBean  containsBean 区别
        // org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(org.springframework.beans.factory.ListableBeanFactory, java.lang.Class<T>, boolean, boolean)
        System.out.println("当前bean工厂查找user bean: " + beanFactory.getBean("user"));
        System.out.println("当前bean工厂是否包含本地user bean: " + beanFactory.containsLocalBean("user"));

        System.out.println("父bean工厂查找user bean: " + beanFactory.getParentBeanFactory().getBean("user"));
        System.out.println("父bean工厂是否包含本地user bean: " + parentBeanFactory.containsLocalBean("user"));

        applicationContext.close();

    }

    public static DefaultListableBeanFactory loadBeanFactory() {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        BeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
        // 装载配置
        beanDefinitionReader.loadBeanDefinitions("classpath:/META-INF/dependency-lookup-context.xml");

        return beanFactory;
    }

}
